define(['./module'], function (services) {
  'use strict';
  services.factory('Auth', ['$http', '$resource', '$cookieStore', function ($http, $resource, $cookieStore) {
    var accessLevels = routingConfig.accessLevels
      , userRoles = routingConfig.userRoles
      , currentUser = $cookieStore.get('user') || {username: '', role: userRoles.public};

    $cookieStore.remove('user');

    function changeUser(user) {
      angular.extend(currentUser, user);
    }

    return {
      authorize: function (accessLevel, role) {
        if (role === undefined) {
          role = currentUser.role;
        }
        //return accessLevel.bitMask & role.bitMask;
        return true
      },
      isLoggedIn: function (user) {
        if (user === undefined) {
          user = currentUser;
        }
        return user.role.title === userRoles.user.title || user.role.title === userRoles.admin.title;
      },
      register: function (user, success, error) {
        $http.post('/register', user).success(function (res) {
          changeUser(res);
          success();
        }).error(error);
      },
      login: function (user, success, error) {
        var user = {
          id: 1,
          username: "user",
          password: "123",
          role: {bitMask: 6, title: 'admin'}
        }
        changeUser(user);
        success(user);
        //
        //$http.post('/login', user).success(function (user) {
        //  changeUser(user);
        //  success(user);
        //}).error(error);
      },
      logout: function (success, error) {
        $http.post('/logout').success(function () {
          changeUser({
            username: '',
            role: userRoles.public
          });
          success();
        }).error(error);
      },
      accessLevels: accessLevels,
      userRoles: userRoles,
      user: currentUser
    };
  }]);
});
